var express = require('express');
var router = express.Router();
var request = require('request');

const config = require('../config');
// var mainUrl = config.mainUrl;
// var apiUrl = config.apiUrl;

const bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());

router.get('/', function (req, res, next) {
    var code = req.query.code;
    console.log(code)

    request.get({
        uri: 'https://api.weixin.qq.com/sns/jscode2session',
        json: true,
        qs: {
            grant_type: 'authorization_code',
            appid: config.xcx_config.AppID,
            secret: config.xcx_config.AppSecret,
            js_code: code
        }
    }, (err, response, data) => {
        if (response.statusCode === 200) {

            // console.log("[openid]", data)
            // console.log("[openid]", data.openid)
            // console.log("[session_key]", data.session_key)

            //TODO: 生成一个唯一字符串sessionid作为键，将openid和session_key作为值，存入redis，超时时间设置为2小时
            // redisStore.set(sessionid, openid + session_key, 7200)
            // 伪代码: redisStore.set(sessionid, openid + session_key, 7200)
            res.json({ openid: data.openid,session_key: data.session_key})
        } else {
            console.log("[error]", err)
            res.json(err)
        }
    })
})
module.exports = router;